(function () {
	/***
	 * chuck 20170226 签订前要点审批，流程业务
	 */
	var serverData = {};
    var serverTable;
    serverData.beforeId = jQuery('#beforeId').val();
    var serverData1 = {};
    var serverTable1;
	//选择审批级数时的变化
	jQuery('#auditorNumber').change(function() {
		var n = jQuery(this).val();
		jQuery("input[name*='ai']").each(function() {
			var index = jQuery(this).prop('id').substr(-1);
			var parent = jQuery(this).parent().parent();
			if (index > n)
				parent.addClass('hide');
			else
				parent.removeClass('hide');
		});
	});
	// 合同提交审批
	jQuery(".app-btn-submit").on(
			'click',
			function() {
				var num = jQuery("#auditorNumber").val();
				for(var i=1;i<=num;i++){
					var val= jQuery("#ai"+i).val();
					if(!val){
						message('审批人没有指定！');
						return;
					}
				}
				if (contractCode==""){
					contractCode = jQuery('#cContractCode').val();
				}
				$.springLemonDialog({
					content : '确认提交审批：' + contractCode + '？',// 确认文本
					clickButton : function(sender, modal, index) {// 按钮事件处理
						// index:0 确认 1：取消
						// sender:事件源 如按钮，sender.html()可得到按钮文字如：取消
						if (index == 0) {
							var flag = 0;
							if(jQuery("#contractAtrrForm") 
									&& !jQuery("#contractAtrrForm").Validform({
										tiptype:3,
										showAllError:true
										}).check(false)){
								flag = 1;
					        };
							var n = jQuery('#auditorNumber').val();
							jQuery("input[name*='ai']").each(function() {
								var index = jQuery(this).prop('id').substr(-1);
								var parent = jQuery(this).parent().parent();
								if (index <= n) {
									if (jQuery(parent)
											&& !jQuery(parent).Validform({
												tiptype : 3,
												showAllError : true
											}).check(false)) {
										flag = 1;
									}
									;
								}
							}); 
							if (flag==0){
								auditBeforeContract($("#beforeId").val());
							}
						}
						$(this).closeDialog(modal);
					}
				});

			});

	// 引入客户信息弹窗
	jQuery('.btn-find-auditor').on("click", function() {
		currentAuditor = jQuery(this).prop('id');
		jQuery("#modal-find-auditor").modal('show');
		jQuery("#modal-find-auditor input[type='radio']").attr('checked', false);
	});

	// 用户查找弹窗
	var serverUserData = {};
	serverUserTable = jQuery('#table-user')
			.DataTable(
					{
						"serverSide" : true,
						"iDisplayLength" : 4,
						"ordering" : false,
						"ajax" : {
							"dataType" : "json",
							"type" : "get",
							"cache" : false,
							"url" : window.rootPath + '/ui/user/getpage',
							"data" : function(d) {
								return $.extend({}, d, serverUserData);
							}
						},
						columns : [
								{
									// 1序号
									data : null,
					                defaultContent : ""// 排序   1
								},
								{// 2姓名
									data : "empLogin.name",
								},
								{// 3性别
									data : 'sex'
								},

								{// 4职务
									data : 'position'
								},
								{// 5销售区域
									data : 'saleArea.superiorArea'
								},
								{// 6选择按钮
									data : null,
									render : function() {
										var html = "<input type='radio' name='btn-select' class='app-select-user'/>"
										return html;
									}
								}

						],
						"drawCallback" : function(oSettings) {
							var k = 0;
							var total = oSettings.aiDisplay.length
									+ oSettings._iDisplayStart;

							for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
								$(
										'td:eq(0)',
										oSettings.aoData[oSettings.aiDisplay[k]].nTr)
										.text(i + 1);
								k++;
							}

							serverUserTable.off('click', 'tr');
							serverUserTable
									.on(
											'click',
											'tr',
											function(event) {
												event = event || window.event;
												var target = event.target
														|| event.scrElement;
												var data = serverUserTable
														.row(this).data();

												if (target.className
														.indexOf('app-select-user') != -1) {
													onSelectUser(data);
												}
												return;
											});
						}
					});// end of datatable
	var selectedUser = null;
	var currentAuditor = null;
	var onSelectUser = function onSelectUser(data) {
		selectedUser = data;
	};

	// 引入用户按钮
	jQuery('#btn-reference').on('click', function() {
		if (selectedUser && currentAuditor) {
			jQuery("#ai" + currentAuditor).val(selectedUser.empLogin.name);
			jQuery("#auditor" + currentAuditor).val(selectedUser.id);
		}

		selectedUser = null;
		currentAuditor = null;
		jQuery("#modal-find-auditor").modal('hide');
	});
	// 查找用户返回按钮
	jQuery('.app-find-user-return').on('click', function() {
		selectedUser = null;
		currentAuditor = null;
	});
	
	// 查询
	jQuery('.app-search-btn').on('click', function() {
		serverUserData.key = jQuery("#search").val();
		serverUserTable.draw();
	});
	// 撤销查询
	jQuery('.app-reset-btn').on('click', function() {
		jQuery('#search').val('');
		serverUserData.key = '';
		serverUserTable.draw();
	});
	
	
	// 查询
	jQuery('.app-btn-search').on('click', function() {
		serverUserData.key = jQuery("#search1").val();
		serverUserTable.draw();
	});
	// 撤销查询
	jQuery('.app-btn-reset').on('click', function() {
		jQuery('#search1').val('');
		serverUserData.key = '';
		serverUserTable.draw();
	});


	/**
	 * 提交合同审批
	 */
	var auditBeforeContract = function(beforeId) {
		var cProjectName = jQuery("#cProjectName").val();
		var url = window.rootPath + "/ui/beforecontract/audit-submit/" + beforeId+"?cProjectName="+cProjectName;

		jQuery.post(encodeURI(url),
		{
		"auditorNumber" : jQuery("#auditorNumber").val(),
		"auditor1" : jQuery("#auditor1").val(),
		"auditor2" : jQuery("#auditor2").val(),
		"auditor3" : jQuery("#auditor3").val(),
		"auditor4" : jQuery("#auditor4").val(),
		"auditor5" : jQuery("#auditor5").val(),
		"auditor6" : jQuery("#auditor6").val(),
		"auditor7" : jQuery("#auditor7").val(),
		"auditor8" : jQuery("#auditor8").val()
		}, function(data) {
			if (data.code == 0) {
				jQuery(".app-btn-submit").attr("disabled", false);
				window.location = window.rootPath + "/ui/beforecontract/";
			}
		});
	}
	
	jQuery(document).ready(function (){
		/**
		 * 会签界面List数据获取
		 */
		serverTable = jQuery('#BeforeContractHQDetailTab').DataTable({
		    "serverSide" : true,
		    "ordering" : false,
		    "ajax" : {
		        "dataType" : "json",
		        "type" : "post",
		        "cache" : false,
		        "url" : window.rootPath+ '/ui/beforecontract/exdebeforecontractdetailHQ/getpage',
		        "data": function (d) {
        			return $.extend({}, d, serverData);
        		}
		    },
		    "columns" : [{
					        data : null
					    },
		                {
		    	            data: null,
		    	            defaultContent: "",
		    	            render: function (data, type, full, meta) {
		    	            	var id=data.id
		    	            	var operate ='<input type="checkbox" class="checkchildContract">';
		    	            	return operate;
		    	            }   
		                },
		                {
		                    data : 'cUserName'//审批人名称
		                },
		                {
		                    data : 'cAuditMemo'//审批说明1
		                },
		                {
                          	data: 'cAuditState',
                            render: function (data, type, full, meta) {
                             	var dOut;
                             	 if(data==0){
                             		dOut = '<td class="center" ><span class="badge label-pill label-primary">未审批</span></td>';
                             	}
                             	else if(data==1){
                             		dOut = '<td class="center" ><span class="badge label-pill label-danger">已审批</span></td>';
                             	}
             	            	return dOut;
                             }
                        },
		                /*{
		                    data : 'cAuditState'//审批状态（0:未审批,1:已审批）
		                },*/
		                {
		                    data : 'dAuditSubmitDate',//审批通过时间
		                    render: function (data, type, full, meta) {
		  	                      if (data)
		  	                         return moment(data).format('YYYY/MM/DD');
		  	                    else
		  	                         return '';
		  	                    }
		                }],
		    "drawCallback": function (oSettings) {
		        var k = 0;
		        var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

		        for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
		            $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
		            k++;
		        }
		    }
		});
		/**
		 * 会签人新增界面人员List数据获取
		 */
		serverData1.key = "";
		serverTable1 = jQuery('#BeforeContractDetailUserTab').DataTable({
		    "serverSide" : true,
		    "ordering" : false,
		    "ajax" : {
		        "dataType" : "json",
		        "type" : "post",
		        "cache" : false,
		        "url" : window.rootPath+ '/ui/beforecontract/user/getpage',
		        "data": function (d) {
        			return $.extend({}, d, serverData1);
        		}
		    },
		    "columns" : [{
					        data : null,
					        defaultContent : ""// 排序   1
					    },
		                {
		    	            data: null,
		    	            defaultContent: "",
		    	            render: function (data, type, full, meta) {
		    	            	var id=data.id
		    	            	var operate ='<input type="checkbox" class="checkchildContract">';
		    	            	return operate;
		    	            }   
		                },
		                {
		                    data : 'empLogin.name'//姓名
		                },
		                {// 3性别
							data : 'sex'
						},

						{// 4职务
							data : 'position'
						},
		                {
		                    data : 'saleArea.superiorArea'//片区名称
		                }],
		    "drawCallback": function (oSettings) {
		        var k = 0;
		        var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

		        for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
		            $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
		            k++;
		        }
		    }
		});
	});

	//合同签订前审批会签人新增
	jQuery('#personSaveBtn').on("click",function(){
		serverData1.key = "";
		//serverTable1.draw();
		jQuery("#huiQian_person").modal('show');
	});
	//合同签订前审批会签人dialog保存
	jQuery('#person_save').on("click",function(){
		var selects=getSelect("#BeforeContractDetailUserTab",1);
			$.springLemonDialog({
		         content: '即将保存该界面信息，是否继续？',// 确认文本
		         clickButton: function (sender, modal, index) {// 按钮事件处理
		             $(this).closeDialog(modal);
		             for(var i=0;i<selects.length;i++){
						if (jQuery("#huiQian_personForm") && !jQuery("#huiQian_personForm").Validform({
							tiptype : 3,
							showAllError : true
						}).check(false)) {return;}
						jQuery("#person_save").attr("disabled","disabled");
						var api = window.rootPath + "/ui/beforecontract/saveExdeBeforeContractCounterSign";
						var d={
								"exdeBeforeContract":{"id":$("#beforeId").val()},
								//"exdeBeforeContract":{"id":selects[i].id},
								//"cUserName" : $("#cUserName_person").val(),
								"cUserName" : selects[i].empLogin.name,
								"id" : " ",
								"user":{"id":selects[i].id},
								"cAuditState":0
						};
						jQuery.ajax({
							type : 'post',
							url : api,
							data : JSON.stringify(d),
							dataType : 'json',
							contentType : 'application/json;charset=utf-8',
							success : function(data) {
								serverData.beforeId = $('#beforeId').val();
								serverTable.draw();
								jQuery("#person_save").removeAttr("disabled");
								jQuery('#huiQian_person').modal('hide');
							}
						});
		             }
		     }
		 });
		
	});
	//合同签订前审批会签人dialog删除
	jQuery('#personDeleteBtn').on("click",function(){
        var selects=getSelect("#BeforeContractHQDetailTab",1);
 	   if(selects.length==0){
 		   $.springLemonDialog({
 		         content: '请选择要删除的记录',// 确认文本
 		         clickButton: function (sender, modal, index) {// 按钮事件处理
 		             $(this).closeDialog(modal);
 		         }
 		   }); 
 	   }else{
 		   var ids= "";
 		   for(var i=0;i<selects.length;i++){
 			   ids += selects[i].id + ",";  
 		   }
 		   if(ids != ""){
 			   ids = ids.substring(ids,ids.length-1);
 		   }
 		   var api=window.rootPath + "/ui/beforecontract/deleteExdeBeforeContractCounterSigns?ids="+ids;
 		   $.springLemonDialog({
 		         content: '确认删除'+selects.length+'条记录？',// 确认文本
 		         clickButton: function (sender, modal, index) {// 按钮事件处理
 		        	 if (index == 0) {
 		        		 jQuery.ajax({
 		        			    url:encodeURI(api),
 		        	            cache:false,
 		        	            type :"get",
 		        	            dataType:"json",
 		        	            contentType:"application/json;charset=utf-8",//解决返回数据中的中文乱码问题
 		        	            success:function(data){
 		        	            	serverData.beforeId = $('#beforeId').val();
 		    						serverTable.draw();
 		        	            }
 		        	        });	
 		        	 }
 		             $(this).closeDialog(modal);
 		         }
 		       });
 	   }
     });
	//会签人新增dialog中查询按钮
	jQuery('#search_btn').on('click',function(){
        serverData1.key=jQuery('#search').val();
        serverTable1.draw();
    })
})();